package com.example.study.config;

/**
 * @Author：路飞4
 * @email：15833013864@163.com
 * @Date：2023/3/1 11:56
 * 描述:线程池配置
 */

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync//开启异步调用
public class ThreadPoolConfig {
    /**
     * 获取服务器的cpu个数
     */
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int COUR_SIZE = CPU_COUNT * 2;
    private static final int MAX_COUR_SIZE = CPU_COUNT * 4;


    /**
     * @return 接下来配置一个bean，配置线程池
     */
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //给threadPoolTaskExecutor设置核心线程数COUR_SIZE
        threadPoolTaskExecutor.setCorePoolSize(COUR_SIZE);
        // 配置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(MAX_COUR_SIZE);
        //配置队列容量（这里设置成最大线程数的四倍)
        threadPoolTaskExecutor.setQueueCapacity(MAX_COUR_SIZE * 4);
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        // 给线程池设置名称
        threadPoolTaskExecutor.setThreadNamePrefix("threadPoolExecutor-");
        // 设置任务的拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }


}
